using System;
using System.CodeDom;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

namespace CodeDom
{
  internal class DateTimeFieldPropertyGenerator : TemplateFieldGenerator
  {
    public DateTimeFieldPropertyGenerator(TemplateField field)
      : base(field)
    {
    }

    #region Overrides of FieldPropertyGenerator

    public override void AddValueConversionStatements(CodeExpression itemReference, CodeMemberMethod method)
    {
      method.Statements.Add(CreateFieldValueVariableStatement(itemReference));
      CreateReturnNullStatement(method);
      CreateReturnDateTimeStatement(method);
    }

    public override CodeTypeReference GetFieldType()
    {
      return new CodeTypeReference("DateTime?");
    }

    private void CreateReturnDateTimeStatement(CodeMemberMethod method)
    {
      var dateConversionStatement = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("DateUtil"), "IsoDateToDateTime", new CodeVariableReferenceExpression("fieldValue"));
      var returnDateStatement = new CodeMethodReturnStatement(dateConversionStatement);
      method.Statements.Add(returnDateStatement);
    }

    private void CreateReturnNullStatement(CodeMemberMethod method)
    {
      var nullCheck = CreateNullCheck(new CodeVariableReferenceExpression("fieldValue"));
      var returnNullStatement = new CodeMethodReturnStatement(new CodePrimitiveExpression(null));
      var returnIfNullStatement = new CodeConditionStatement(nullCheck, returnNullStatement);
      method.Statements.Add(returnIfNullStatement);
    }

    #endregion
  }
}